import React, { useState } from 'react';
import styles from './index.less';
import { Select, Form, Button, DatePicker, ConfigProvider } from 'antd';
import zhCN from 'antd/es/locale/zh_CN';
import { useDebounceFn } from 'ahooks';
import moment from 'moment';

import { HttpCode } from '#/utils/contacts.js';
import { Pointer, PageLoading, TRDefault } from '@/components/index.js';
import {
  continuousAverageOptions,
  pointConvert,
} from '@/pages/ETrade/MediumAndLongTermMarket/constant.js';
import { fetchGetMarketSupDemRelation } from '@/pages/ETrade/MediumAndLongTermMarket/services.js';
import BaseTable from '../BaseTable';
import { ChartMarketSupplyDemandRelationship } from '../Charts/index.js';

const { RangePicker } = DatePicker;
const dateFormat = 'YYYYMMDD';

const MarketSupplyDemandRelationship = (props: any) => {
  const {
    marketList,
    marketId,
    provinceList,
    provinceId,
    date,
    remSize,
    unitId,
    point,
    continuousAverage: contAve,
  } = props;
  const [loading, setLoading] = useState(true),
    [marketSupDemRelation, setMarketSupDemRelation] = useState<any>(),
    [tableData, setTableData] = useState<any>([]),
    [tableHeader, setTableHeader] = useState<any>([]),
    [form] = Form.useForm();

  React.useEffect(() => {
    form.submit();
  }, []);

  const getMarketSupDemRelation = async (values: any) => {
    setLoading(true);
    setTableData([]);
    const param = {
      provinceId: values.region,
      stationId: unitId,
      timeOrder: values.point,
      type: values.contAve === '连续' ? 'con' : 'avg',
      startDate: moment(values.date[0]).format('YYYY-MM-DD'),
      endDate: moment(values.date[1]).format('YYYY-MM-DD'),
    };
    const res = await fetchGetMarketSupDemRelation(param);
    setLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      if (!res.data) return;
      const data = res.data;
      const XAXIS: any = [],
        water: any = [],
        fire: any = [],
        newEnergy: any = [],
        newEnergy_1: any = [],
        newEnergy_2: any = [],
        newEnergy_3: any = [];
      let count = 0;
      Object.entries(data).map((t: any, i) => {
        t[1].forEach((_t: any) => {
          count++;
          if (i === 0) {
            Array.from({ length: values.point }, (_t_, _i_) => {
              param.type === 'con'
                ? XAXIS.push(
                    `${moment(_t.date).format('MMDD')} ${pointConvert(
                      _i_ + 1,
                      parseInt(values.point),
                    )}`,
                  )
                : XAXIS.push(`${pointConvert(_i_ + 1, parseInt(values.point))}`);
            });
          }
          if (!_t.values?.length) {
            count--;
            Array.from({ length: param.timeOrder }, () => {
              if (t[0] === '新能源预测-DW') {
                newEnergy.push('-');
              }
              if (t[0] === '火电最小') {
                fire.push('-');
              }
              if (t[0] === '水电发力') {
                water.push('-');
              }
              if (t[0] === '新能源预测-XZ') {
                newEnergy_1.push('-');
              }
              if (t[0] === '新能源预测-DR') {
                newEnergy_2.push('-');
              }
              if (t[0] === '新能源预测-HN') {
                newEnergy_3.push('-');
              }
            });
          }
          (_t.values || []).forEach((_t_: any) => {
            if (t[0] === '新能源预测-DW') {
              newEnergy.push(_t_);
            }
            if (t[0] === '火电最小') {
              fire.push(_t_);
            }
            if (t[0] === '水电发力') {
              water.push(_t_);
            }
            if (t[0] === '新能源预测-XZ') {
              newEnergy_1.push(_t_);
            }
            if (t[0] === '新能源预测-DR') {
              newEnergy_2.push(_t_);
            }
            if (t[0] === '新能源预测-HN') {
              newEnergy_3.push(_t_);
            }
          });
        });
      });
      if (count < 1) {
        setMarketSupDemRelation({});
        return;
      } else {
        setMarketSupDemRelation({
          XAXIS,
          water,
          fire,
          newEnergy,
          newEnergy_1,
          newEnergy_2,
          newEnergy_3,
        });
      }

      const _tableData: any = [
        {
          title: '火电最小',
        },
        {
          title: '水电发力',
        },
        {
          title: '新能源出力1',
        },
        {
          title: '新能源出力2',
        },
        {
          title: '新能源出力3',
        },
        {
          title: '新能源出力4',
        },
      ];
      XAXIS.forEach((t: any, i: any) => {
        _tableData[0][t] = fire[i];
        _tableData[1][t] = water[i];
        _tableData[2][t] = newEnergy[i];
        _tableData[3][t] = newEnergy_1[i];
        _tableData[4][t] = newEnergy_2[i];
        _tableData[5][t] = newEnergy_3[i];
      });
      setTableData(_tableData);
      setTableHeader(
        XAXIS.map((t: any) => ({
          name: t,
          field: t,
        })),
      );
    }
  };
  const _onFinish = useDebounceFn(
    (values: any) => {
      getMarketSupDemRelation(values);
    },
    { wait: 500 },
  );
  const initialValues = () => ({
    market: marketId,
    region: provinceId,
    point: point,
    contAve: contAve,
    date: date,
  });
  const _onReset = useDebounceFn(
    () => {
      form.resetFields();
      form.submit();
    },
    { wait: 500 },
  );
  return (
    <ConfigProvider locale={zhCN}>
      <div className={styles.container}>
        <div className={styles.header}>
          <Form
            form={form}
            initialValues={initialValues()}
            className={styles.formStyles}
            onFinish={_onFinish.run}
          >
            <Form.Item
              name="market"
              className={styles.cell_item}
              rules={[{ required: true, message: '请选择省份' }]}
            >
              <Select
                style={{ width: 200 }}
                placeholder="选择省份"
                showSearch
                options={marketList}
                onChange={(e: any, { provinceId }: any) => {
                  form.setFieldsValue({ region: provinceId });
                }}
                filterOption={(input, option) => {
                  return (option?.label as unknown as string)
                    .toLowerCase()
                    .includes(input.toLowerCase());
                }}
              />
            </Form.Item>
            <Form.Item noStyle name="region" />
            <Form.Item name="point" className={styles.cell_item}>
              <Pointer
                className={styles.font}
                data={point}
                onChange={(e: any) => {
                  form.setFieldsValue({ point: e.target.value });
                }}
              />
            </Form.Item>
            <Form.Item
              name="contAve"
              className={styles.cell_item}
              rules={[{ required: true, message: '请选择月份' }]}
            >
              <Pointer className={styles.font} options={continuousAverageOptions} data={contAve} />
            </Form.Item>
            <Form.Item
              name="date"
              className={styles.cell_item}
              rules={[{ required: true, message: '请选择日期' }]}
            >
              <RangePicker
                className={styles.font}
                style={{ width: 260 }}
                format={dateFormat}
                separator={'-'}
              />
            </Form.Item>
            <Button className={styles.submit} type="primary" htmlType="submit">
              查询
            </Button>
            <Button className={styles.reset} htmlType="reset" onClick={_onReset.run} ghost>
              重置
            </Button>
          </Form>
        </div>
        {loading ? (
          <PageLoading />
        ) : (
          <div className={styles.content}>
            {tableData?.length ? (
              <>
                <div style={{ height: 570 }}>
                  <ChartMarketSupplyDemandRelationship
                    data={marketSupDemRelation}
                    scale={remSize / 100}
                  />
                </div>
                <div style={{ paddingBottom: 24, marginTop: 28 }}>
                  <BaseTable tableData={tableData} tableHeader={tableHeader} fixed={true} />
                </div>
              </>
            ) : (
              <TRDefault type="emptysm" />
            )}
          </div>
        )}
      </div>
    </ConfigProvider>
  );
};

export default MarketSupplyDemandRelationship;
